﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace System.Common
{
    /// <summary>
    /// Provides the ability to bind textbox changes whenever the text changes, rather than
    /// when focus is lost.
    /// </summary>
    public class Binding
    {
        /// <summary>
        /// The property that controls whether or not the binding gets updated when the
        /// text changes.
        /// </summary>
        public static readonly DependencyProperty UpdateSourceTriggerProperty =
            DependencyProperty.RegisterAttached("UpdateSourceTrigger",
                typeof(bool),
                typeof(Binding),
                new PropertyMetadata(true, OnUpdateSourceTriggerChanged));

        /// <summary>
        /// The property changed callback.
        /// </summary>
        private static void OnUpdateSourceTriggerChanged(
            DependencyObject obj,
            DependencyPropertyChangedEventArgs args)
        {
            TextBox box = GetSource(obj);
            if (box != null)
            {
                if ((bool)args.NewValue)
                {
                    box.TextChanged += OnChange;
                }
                else
                {
                    box.TextChanged -= OnChange;
                }
            }
        }

        /// <summary>
        /// Handles when text changes in the bound textbox.
        /// </summary>
        private static void OnChange(object sender, TextChangedEventArgs args)
        {
            TextBox box = GetSource(sender);
            if (box != null)
            {
                BindingExpression expression = box.GetBindingExpression(TextBox.TextProperty);
                if (expression != null)
                {
                    expression.UpdateSource();
                }
            }
        }

        /// <summary>
        /// Helper method to get the source textbox.
        /// </summary>
        private static TextBox GetSource(object source)
        {
            return source as TextBox;
        }

        /// <summary>
        /// Get the update source trigger.
        /// </summary>
        public static bool GetUpdateSourceTrigger(DependencyObject obj)
        {
            return (bool)obj.GetValue(UpdateSourceTriggerProperty);
        }

        /// <summary>
        /// Set the update source trigger.
        /// </summary>
        public static void SetUpdateSourceTrigger(DependencyObject obj, object value)
        {
            obj.SetValue(UpdateSourceTriggerProperty, value);
        }
    }
}
